/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: client.c
> Author:cjy
> Mail: 
> Created Time: 2024年08月15日 星期四 15时21分48秒
***************************************************/
// 开发一个多进程计算服务器
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "cJSON.h"
struct data
{
	int type;
	char count[10];
	float num1;
	float num2;
};

struct number
{
	float sum;
};

int main(int argc,const char* argv[])
{
	int sock = 0;
	int ret = 0;

	struct sockaddr_in serAddr;
        memset(&serAddr,0,sizeof(serAddr));

	sock = socket(AF_INET,SOCK_STREAM,0);
	if(sock == -1)
	{
		perror("sock");
		exit(-1);
	}

	serAddr.sin_family = AF_INET;
        serAddr.sin_port = htons(6661);
        serAddr.sin_addr.s_addr = inet_addr("192.168.198.128");

	ret = connect(sock,(struct sockaddr *)&serAddr,sizeof(struct sockaddr));
	if(ret == -1)
	{
		perror("connect");
		exit(-1);
	}

	struct data dat;
	cJSON *json = NULL;
	char *buf = NULL;
	char dest[1024] = {0};
        while(1)
        {	
		printf("1------- 加\n");
		printf("2------- 减\n");
		printf("3------- 乘\n");
		printf("4------- 除\n");
		printf("0------- 退出\n");
		printf("你想进行什么操作:\n");
		scanf("%d",&dat.type);
		if(dat.type == 0){
			break;			
		}
		if(dat.type == 1){
			strcpy(dat.count,"add");
		}
		if(dat.type == 2){
			strcpy(dat.count,"minus");
		}
		if(dat.type == 3){
			strcpy(dat.count,"multiply");
		}
		if(dat.type == 4){
			strcpy(dat.count,"divide");
		}

		printf("请输入数字1:\n");
		scanf("%f",&dat.num1);
		printf("请输入数字2:\n");
		scanf("%f",&dat.num2);
	
		json = cJSON_CreateObject();
		cJSON_AddItemToObject(json,"type",cJSON_CreateNumber(dat.type));
		cJSON_AddItemToObject(json,"count",cJSON_CreateString(dat.count));
		cJSON_AddItemToObject(json,"num1",cJSON_CreateNumber(dat.num1));
		cJSON_AddItemToObject(json,"num2",cJSON_CreateNumber(dat.num2));

		buf = cJSON_Print(json);
		puts(buf);
		ret = send(sock,buf,strlen(buf),0);
		if(ret == -1)
		{
			perror("send");
		}
		struct number num;
		memset(&num,0,sizeof(num));
		ret = recv(sock,dest,sizeof(dest) - 1,0);
		if(ret == -1){
			perror("recv");
			exit(-1);
		}
		puts(dest);
		json = cJSON_Parse(dest);
		cJSON *node = NULL;

		node = cJSON_GetObjectItem(json,"sum");
		if(node == NULL)
		{
			printf("can't find\n");
			exit(-1);
		}
		if(node->type == cJSON_Number)
		{
			num.sum = node->valuedouble;
		}
		
	
		printf("number = %.2f\n",num.sum);
		
		cJSON_Delete(json);
	}

close(sock);

return 0;
}
